package com.hysf.dao.impl;

import com.hysf.dao.AccountDao;
import com.hysf.pojo.Account;
import com.hysf.utils.AccountRowMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import java.sql.PreparedStatement;
import java.util.List;

@Repository
@RequiredArgsConstructor
public class AccountDaoImpl implements AccountDao {
	
	private final JdbcTemplate jdbcTemplate;
	
	@Override
	public int insert(double money) {
		String sql = "insert into accounts (balance) values (?)";
		KeyHolder keyHolder = new GeneratedKeyHolder();
		jdbcTemplate.update(conn -> {
			PreparedStatement ps = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
			ps.setDouble(1, money);
			return ps;
		}, keyHolder);
		return keyHolder.getKey().intValue();
	}
	
	@Override
	public int delete(Integer accountid) {
		String sql = "delete from accounts where accountid = ?";
		return jdbcTemplate.update(sql, accountid);
	}
	
	@Override
	public int update(Integer accountid, double money) {
		String sql = "update accounts set balance = ? where accountid = ?";
		return jdbcTemplate.update(sql, money, accountid);
	}
	
	@Override
	public int findCount() {
		String sql = "select count(*) from accounts";
		return jdbcTemplate.queryForObject(sql, Integer.class);
	}
	
	@Override
	public List<Account> findAll() {
		String sql = "select * from accounts";
		return jdbcTemplate.query(sql, new AccountRowMapper());
	}
	
	@Override
	public Account findById(Integer accountid) {
		String sql = "select * from accounts where accountid = ?";
		return jdbcTemplate.query(sql, new AccountRowMapper(), accountid).get(0);
	}
}
